<?php

namespace App\Http\Controllers\api\auth;

use App\Common\statement\ResponseStatement;
use App\Http\Requests\auth\AuthRequest;
use App\Http\Controllers\Controller;
use App\Http\Resources\user\UserResource;
use App\Models\user\ThirdLogin;
use App\Models\user\UserCheck;
use App\Services\common\SmsService;
use App\Services\common\UserService;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{


    public function login(AuthRequest $request)
    {

        $params = $request->only(['phone', 'password']);

        if(preg_match('/^\d{4,11}$/', $params['phone'])){
            $credentials['phone'] = $params['phone'];
        }elseif (preg_match("'/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/'",$params['phone'])){
            $credentials['cert_number'] = $params['phone'];
        }else{
            $credentials['name'] = $params['phone'];
        }

        if (!$userInfo = User::where($credentials)->get()){
            return error('用户不存在或被禁用');
        }
        $user = [];
        foreach ($userInfo as $item){
            if(Hash::check($params['password'],$item['password'])){
                $user = $item;break;
            }
        }

        if(!$user){
            return error('密码错误');
        }

        if (!$token = auth('api')->fromUser($user)) {
            return error('密码错误');
        }

        return $this->respondWithToken($token,auth('api')->getUser());
    }


    /**
     * 验证码登录
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function code(AuthRequest $request,SmsService $service)
    {
        $service->smsVerifier($request->phone,$request->code);

        if (!$user = User::where('phone',$request->phone)->first()){

            return error('用户不存在或被禁用');
        }

        if (!$token = auth('api')->fromUser($user)) {
            return error(ResponseStatement::TOKEN_TIME_OUT);
        }

        return $this->respondWithToken($token,$user);
    }


    /**
     * 用户注册
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @throws \App\Exceptions\api\BaseException
     */
    public function register(AuthRequest $request,SmsService $service,UserService $userService)
    {

        $params = $request->only(['phone','code','name','header_img','sex','password','superior_id']);

        if (!empty($params['superior_id']))
        {
            if (is_numeric($params['superior_id'])){
                $params['superior_id'] = User::whereUuid($params['superior_id'])->value('id');
            }else{
                $params['superior_id'] = dehashid($params['superior_id'])??0;
            }
        }else{
            $params['superior_id'] = 0;
        }

        if (isInt($params['superior_id'])){
            $superior = User::whereId($params['superior_id'])->first();
            $params['superior_uuid'] = $superior->uuid;
            if ($superior->cate == 3){
                $params['cate'] = 2;
            }
        }

        $service->smsVerifier($params['phone'],$params['code']);

        $user = $userService->register($params);

        if ($user){
            if (!$token = auth('api')->fromUser($user)) {
                return error(ResponseStatement::TOKEN_TIME_OUT);
            }

            if ($request->level > 1){//注册小店和企业用户
                $map['user_id'] = $user->id;
                $map['level']   = $request->level;
                $map['imgs']   = $request->imgs;
                $map['status']   = 2;
                UserCheck::create($map);
            }

            return $this->respondWithToken($token,$user);
        }

        return error('注册失败');

    }


    /**
     * 重置密码
     */
    public function resetPassword(AuthRequest $request)
    {
        $params = $request->only(['phone','password']);

        $user = User::where('phone',$params['phone'])->first();

        $result = $user->update(['password'=>$params['password']]);

        if ($result){
            return successWithMsg("修改成功");
        }
        return error();

    }

    public function third(AuthRequest $request,UserService $userService)
    {
        $map['open_id'] = $request->open_id;
        $map['app_type'] = $request->app_type??1;

        $third = ThirdLogin::where($map)->first();

        if ($third){//已注册
            $user = $third->user;
            $update = [];
            if ($request->name){
                $update['app_name'] = $request->name;
            }
            if ($request->extend){
                $update['extend'] = $request->extend;
            }
            if (!empty($update)){
                $third->update($update);
            }
        }else{//未注册
            DB::beginTransaction();
            try{
                $params['name'] = $request->name;
                $params['header_img'] = $request->header_img;
                $params['sex'] = $request->sex;
                $params['birthday'] = $request->birthday;
                $user = $userService->register($params);

                $map['user_id'] = $user->id;
                $map['app_name'] = $request->name;
                $map['extend'] = $request->extend;
                ThirdLogin::create($map);
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                return error($e->getMessage());
            }

        }
        if (!$token = auth('api')->fromUser($user)) {
            return error(ResponseStatement::TOKEN_TIME_OUT);
        }

        return $this->respondWithToken($token,$user);

    }
    

    
    

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {

        $user = Auth('api')->user();
        dd($user->extend);
        return success(Auth('api')->id());

    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return successWithMsg('退出成功');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh(),auth()->user());
    }



    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token,$user)
    {
        return success([
            'token'      => 'bearer ' . $token,
            'expires_in' => auth('api')->factory()->getTTL() * 60,
//            'user' => new UserResource($user)
        ],'登录成功');
    }

//    protected function respondWithToken($token,$user)
//    {
//        return success([
//            'token'      => 'bearer ' . $token,
//            'expires_in' => auth('api')->factory()->getTTL() * 60,
//            'rongyun_token' => ImService::getToken($user->id),
//            'user' => new UserResource($user)
//        ],'登录成功');
//    }


}
